package com.xy.smartsms.vista;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;

import com.xy.smartsms.util.Log;

import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.xy.smartsms.data.PublicInfoData;
import com.xy.smartsms.presenter.ComposePresenter;
import com.xy.smartsms.presenter.ComposePresenterImpl;
import com.xy.smartsms.util.NavBarUtil;

import java.util.List;
import java.util.Map;

import cn.cmcc.online.smsapi.ui.util.DensityUtil;

/**
 * 提供菜单公众号的视图和交互（进入会话）
 */
public class ComposeViewHolder implements ComposeVista {
    private final static String TAG = ComposeViewHolder.class.getSimpleName();

    /**
     * 菜单的顶层资源ID
     */
    public static final String ID_STUB = "ID_STUB";
    /**
     * 菜单和编辑的切换资源ID
     */
    public static final String ID_CHANGE2MENU = "ID_CHANGE2MENU";
    public static final String ID_CHANGE2INPUT = "ID_CHANGE2INPUT";
    /**
     * 编辑界面的顶层资源ID
     */
    public static final String ID_EDIT = "ID_EDIT";
    /**
     * 自动显示短信公众号菜单；默认打开
     */
    public static final String FUNC_AUTO_MENU = "FUNC_AUTO_MENU";

    private View mEditRootLayout = null;
    private View mButtonToXYMenu = null;
    private View mButtonToXYInput = null;
    private LinearLayout mXYMenuRootLayout = null;
    private Activity mContext = null;
    private String mRecipientNumber = null;
    private ComposePresenter mComposePresenter = null;
    private Map<String, String> mConfigMap = null;
    private boolean mFuncAutoMenu = true;
    private OnMenuStatusListener mOnMenuStatusListener = null;

    private PopupWindow mPopupWindow;
    private String mCurrentMenuName;

    /**
     * 构造函数，建议在列表界面的onCreate()中调用
     *
     * @param context
     * @param phone
     */
    public ComposeViewHolder(Activity context, String phone) {
        mContext = context;
        mRecipientNumber = phone;

        if (!TextUtils.isEmpty(mRecipientNumber)) {
            mComposePresenter = new ComposePresenterImpl(mContext);
            mComposePresenter.setData(mRecipientNumber);
            mComposePresenter.setVista(this);
            mComposePresenter.preloadBubble();
        }
    }

    /**
     * 配置资源ID以及功能选择
     *
     * @param map
     */
    public void setMap(Map<String, String> map) {
        mConfigMap = map;
        initVariable();
        loadMenuInner();
    }

    private void initVariable() {
        String config;
        if ((config = mConfigMap.get(ID_EDIT)) != null) {
            mEditRootLayout = mContext.findViewById(Integer.valueOf(config));
        }

        if ((config = mConfigMap.get(ID_STUB)) != null) {
            mXYMenuRootLayout = (LinearLayout) mContext.findViewById(Integer.valueOf(config));
        }

        if ((config = mConfigMap.get(ID_CHANGE2MENU)) != null) {
            mButtonToXYMenu = mContext.findViewById(Integer.valueOf(config));
            if (mButtonToXYMenu != null) {
                mEditRootLayout.setVisibility(View.VISIBLE);
                mButtonToXYMenu.setVisibility(View.GONE);
            }
        }

        if ((config = mConfigMap.get(ID_CHANGE2INPUT)) != null) {
            mButtonToXYInput = mContext.findViewById(Integer.valueOf(config));
        }

        if ((config = mConfigMap.get(FUNC_AUTO_MENU)) != null) {
            mFuncAutoMenu = Boolean.valueOf(config);
        }
    }

    private void loadMenuInner() {
        if (initMenu() && mComposePresenter != null) {
            mComposePresenter.loadMenu();
        }
    }

    private boolean initMenu() {
        if (null == mXYMenuRootLayout || null == mEditRootLayout) {
            return false;
        }

        return true;
    }

    /**
     * 菜单状态回调
     */
    public interface OnMenuStatusListener {
        /**
         * 菜单获取状态
         *
         * @param view null:表示没有菜单；非null:表示菜单的根视图
         */
        void onMenuReady(View view);

        /**
         * 菜单切换状态
         *
         * @param isMenuShow true:表示当前是菜单; false:表示当前是编辑
         */
        void onMenuShow(boolean isMenuShow);
    }

    /**
     * 设置菜单状态获取的回调
     *
     * @param listener
     */
    public void setOnMenuStatusListener(OnMenuStatusListener listener) {
        mOnMenuStatusListener = listener;
    }

    public void destroy() {
        if (mComposePresenter != null) {
            mComposePresenter.clearCache();
        }
    }

    /**
     * 设置为非自动显示时，显示菜单（同时隐藏 编辑）
     */
    public void showMenu() {
        toggleMenu(true);
    }

    private void toggleMenu(boolean show) {
        if (show) {
            mXYMenuRootLayout.setVisibility(View.VISIBLE);
            mEditRootLayout.setVisibility(View.GONE);
        } else {
            mXYMenuRootLayout.setVisibility(View.GONE);
            mEditRootLayout.setVisibility(View.VISIBLE);
        }

        if (mOnMenuStatusListener != null) {
            mOnMenuStatusListener.onMenuShow(show);
        }
    }

    private void bindMenuView(final PublicInfoData data) {
        // Reference cmcc
        List<PublicInfoData.MenuItem> menuList = data.menuList;

        final int dp1 = DensityUtil.dp2px(mContext, 1);
        final int dp44 = DensityUtil.dp2px(mContext, 44);
        final int dp8 = DensityUtil.dp2px(mContext, 8);

        for (final PublicInfoData.MenuItem menu : menuList) {
            final String name = menu.name;
            final List<PublicInfoData.SubMenuItem> subMenuList = menu.subMenuList;

            TextView tv = new TextView(mContext);
            GradientDrawable shapeRectWhite = new GradientDrawable();
            shapeRectWhite.setShape(GradientDrawable.RECTANGLE);
            shapeRectWhite.setColor(Color.parseColor("#ffffff"));
            shapeRectWhite.setStroke(dp1 / 2, Color.parseColor("#D2D2D2"));

            GradientDrawable shapeRectGray = new GradientDrawable();
            shapeRectGray.setShape(GradientDrawable.RECTANGLE);
            shapeRectGray.setColor(Color.parseColor("#D2D2D2"));
            shapeRectGray.setStroke(dp1 / 2, Color.parseColor("#D2D2D2"));

            StateListDrawable selectorRect = new StateListDrawable();
            selectorRect.addState(new int[]{}, shapeRectWhite);
            selectorRect.addState(new int[]{android.R.attr.state_pressed}, shapeRectGray);

            tv.setBackgroundDrawable(selectorRect);
            tv.setText(name);
            tv.setTextColor(Color.parseColor("#7A7A7A"));
            tv.setLayoutParams(new LinearLayout.LayoutParams(0, -1, 1));
            tv.setGravity(Gravity.CENTER);
            tv.setTextSize(14);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCurrentMenuName = menu.name;
                    if (subMenuList != null && subMenuList.size() > 0) {
                        LinearLayout contentView = new LinearLayout(mContext);
                        contentView.setLayoutParams(new LinearLayout.LayoutParams(-1, -1));
                        contentView.setOrientation(LinearLayout.VERTICAL);
                        GradientDrawable shapeRectWhite = new GradientDrawable();
                        shapeRectWhite.setShape(GradientDrawable.RECTANGLE);
                        shapeRectWhite.setColor(Color.parseColor("#ffffff"));
                        shapeRectWhite.setStroke(dp1, Color.parseColor("#D2D2D2"));
                        contentView.setBackgroundDrawable(shapeRectWhite);
                        for (final PublicInfoData.SubMenuItem subMenu : subMenuList) {
                            TextView tvMenu = new TextView(mContext);
                            tvMenu.setLayoutParams(new LinearLayout.LayoutParams(-1, dp44));
                            tvMenu.setPadding(0, dp8, 0, dp8);
                            tvMenu.setGravity(Gravity.CENTER);
                            tvMenu.setTextSize(14);
                            tvMenu.setTextColor(Color.parseColor("#7A7A7A"));
                            tvMenu.setText(subMenu.name);
                            tvMenu.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mComposePresenter.processMenuAction(subMenu.json);
                                    if (mPopupWindow != null) {
                                        mPopupWindow.dismiss();
                                    }
                                }
                            });
                            contentView.addView(tvMenu);
                        }
                        if (mPopupWindow == null) {
                            mPopupWindow = new PopupWindow(contentView, v.getWidth(), -2, true);
                            mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
                            mPopupWindow.setOutsideTouchable(true);
                        } else {
                            mPopupWindow.setContentView(contentView);
                        }
                        int navHeight = 0;
                        if (NavBarUtil.hasDeviceHasNavBar(mContext)) {
                            navHeight = NavBarUtil.getNavBarHeight(mContext);
                        }
                        int distanceMenu = DensityUtil.dp2px(mContext, 4);
                        mPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.LEFT, v.getLeft(), navHeight + v.getHeight() + distanceMenu);
                    } else {
                        mComposePresenter.processMenuAction(menu.json);
                        if (mPopupWindow != null) {
                            mPopupWindow.dismiss();
                        }
                    }
                }
            });
            mXYMenuRootLayout.addView(tv);
        }
    }

    // ComposeVista start
    @Override
    public void showMenu(PublicInfoData menuData) {
        if (menuData == null || menuData.menuList == null || menuData.menuList.size() == 0) {
            mXYMenuRootLayout.setVisibility(View.GONE);
            if (mOnMenuStatusListener != null) {
                mOnMenuStatusListener.onMenuReady(null);
            }

            return;
        }

        Log.i(TAG, "showMenu: " + menuData.json);
        bindMenuView(menuData);
//        mButtonToXYMenu.setVisibility(View.VISIBLE);
//        mButtonToXYMenu.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                toggleMenu(true);
//            }
//        });
//        mButtonToXYInput.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                toggleMenu(false);
//            }
//        });

        if (mFuncAutoMenu) {
            toggleMenu(true);
        }

        if (mOnMenuStatusListener != null) {
            mOnMenuStatusListener.onMenuReady(mXYMenuRootLayout);
        }
    }
    // ComposeVista end
}
